// require modules
const argv = require('minimist')(process.argv.slice(2)); // 用来获取命令行传来的参数
var fs = require('fs');
var archiver = require('archiver');
var path = require('path');

/* 打包环境用来区分 正式包还是测试包 */
const isProduction = argv['build_env'] === 'production';
console.log('打包环境为：', argv['build_env']);
console.log('文件压缩中...');
// 创建一个文件来流  数据, 即将文件压缩得到的文件地址。
var output = fs.createWriteStream( path.resolve(__dirname, isProduction ? './build.zip' : './build.test.zip') );
var archive = archiver('zip', {
    zlib: { level: 9 } // 设置压缩级别.
});

// listen for all archive data to be written
// 'close' event is fired only when a file descriptor is involved
output.on('close', function() {
    // console.log('压缩包地址为：', path.resolve(__dirname, '../build.test','build.test.zip'));
    console.log('压缩包地址为：', path.resolve(__dirname, isProduction ? './build/build.zip': './build.test/build.test.zip'));
    console.log('压缩包大小', archive.pointer() + ' total bytes');
    console.log('压缩程序已经完成，输出文件描述符已经关闭/archiver has been finalized and the output file descriptor has closed.');
});

// This event is fired when the data source is drained no matter what was the data source.
// It is not part of this library but rather from the NodeJS Stream API.
// @see: https://nodejs.org/api/stream.html#stream_event_end
output.on('end', function() {
    console.log('数据流已流完 / Data has been drained');
});

// good practice to catch warnings (ie stat failures and other non-blocking errors)
archive.on('warning', function(err) {
    if (err.code === 'ENOENT') {
        // log warning
        console.warn('stat故障和其他非阻塞错误');
    } else {
        // throw error
        throw err;
    }
});

// good practice to catch this error explicitly
archive.on('error', function(err) {
    console.error('压缩文件出错');
    throw err;
});

archive.on('finish', function (err){
    if(err) throw err;
    var sourceFile = path.resolve(__dirname, isProduction ? './build.zip' : './build.test.zip');
    var destPath = path.resolve(__dirname, isProduction ? './build/build.zip' : './build.test/build.test.zip');
    
    
    fs.rename(sourceFile, destPath, function (err){
        if(err) throw err;
        console.log('压缩包文件移动成功');
    });
    // 移动文件
    console.log('压缩包文件移动中...');
});

// pipe archive data to the file
// 通过管道将数据归档到压缩文件
archive.pipe(output);


var fileDirPath = path.resolve(__dirname, isProduction ? './build' : './build.test');
archive.directory(fileDirPath, false);


// 压缩文件
// finalize the archive (ie we are done appending files but streams have to finish yet)
// 'close', 'end' or 'finish' may be fired right after calling this method so register to them beforehand
archive.finalize();